package jzqb.config;

import com.alibaba.fastjson.JSON;
import haha.life.normal.TokenUtils;
import jzqb.common.Result;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){
           return true;
       }
        String token = request.getHeader("token");
        String currentUserId = TokenUtils.checkTokenReturnID(token);
        if(null==(currentUserId)){
            String result = JSON.toJSONString(Result.tokenFail());
            returnJson(response, result);
            return false;
        }
        return true;
    }

    private void returnJson(HttpServletResponse response, String result) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(result);

        } catch (IOException e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }

    }
}
